<template>
  <div class="hearing">
    <crumb />
    <div class="container">
      <div class="box-left">
        <div class="task-name">任务名称：{{hearingData.resourceHearingName}}
          <i class="el-icon-question cursor" @click="openFunc"></i></div>
        <div class="resourceTrainingContentEn" v-if="hearingData.chapterType==='1'">
          <span>{{hearingData.fileUrl}}</span>
        </div>
        <!-- 图片 -->
        <div class="media-box" v-if="hearingData.chapterType === '2'">
          <img :src="hearingData.fileUrl" style="width:100%">
        </div>
        <!-- 音频 -->
        <div class="media-box" v-if="hearingData.chapterType === '3'">
          <audio class="audio" controls :src="hearingData.fileUrl"></audio>
        </div>
        <!-- 视频 -->
        <div class="media-box" v-if="hearingData.chapterType === '4'">
          <video class="video" :src="hearingData.fileUrl" controls  @ended="updateProcessRate()">
            <track :src="hearingData.subtitlesEnUrl" srclang="en" label="English" kind="subtitles" default />
          </video>
        </div>

        <div class="answer">
          <div class="quesTitle">答题卡</div>
          <div class="questionBtn">
            <div class="qBtn cursor" v-for="(item, index) in resultArr" :key="index"
                 :class="`${cardActive(item,index)}`" @click="toggleTopic(index)">
              <span>
                {{ index+1 }}
              </span>
            </div>
          </div>
        </div>
<!--        <div class="answer-panel">-->
<!--          <ul>-->
<!--            <li v-for="(item,index) in resultArr" :key="index" @click="toggleTopic(index)" :class="`${cardActive(item)}`">{{item.sort_index}}</li>-->
<!--          </ul>-->
<!--        </div>-->
      </div>
      <div class="box-right" v-if="currentItem">
        <!-- <div class="read">
          <h6 class="read-title">阅读环节</h6>
          <p class="read-desc">阅读环节需听完第一遍录音，无法拖动播放进度</p>
          <el-button type="primary" disabled>进入听写</el-button>
        </div> -->
        <div class="hear">

          <div class="question-top">
            <span>题量：</span>
            <span class="now-index">{{ currentIndex + 1 }}</span>
            <span class="total">/{{ subjectList.length }}</span>
            <span class="time">耗时:{{timerDuration}}</span>
          </div>
          <div class="sub-panel">
            <div class="stem">
              {{currentItem.sort_index}}. {{currentItem.subject_content}}
            </div>
            <!-- 10:单选题 -->
            <div class="subject_type_10" v-if="currentItem.subject_type === '10'">
              <div class="item cursor" @click="addResult({type: 10, answerCode: item.answer_code,subjectItemId: item.subject_item_id})" v-for="(item, index) in currentItem.itemList" :key="index">
                <span :class="`chooseBtn cursor ${item.subject_item_id === currentResultItem.subject_item_id ? 'activeChooseBtn' :''}`">{{item.answer_code}}</span>
                <span class="question-content">
                  {{ item.resource_subject_item_tent }}
                </span>
              </div>
            </div>
            <!-- 11:多选题 -->
            <!-- 12:判断题 -->
            <div class="subject_type_12" v-if="currentItem.subject_type === '12'">
              <div class="item cursor" @click="addResult({type: 12,subjectItemTent: item.resource_subject_item_tent,subjectItemId: item.subject_item_id})" v-for="(item, index) in currentItem.itemList" :key="index">
                <span :class="`chooseBtn cursor ${item.subject_item_id === currentResultItem.subject_item_id ? 'activeChooseBtn' :''}`">{{index === 0?'A':'B'}}</span>
                <span class="question-content">
                  {{ item.resource_subject_item_tent }}
                </span>
              </div>
            </div>
            <!-- 13:填空题 -->
            <div class="subject_type_13" v-if="currentItem.subject_type === '13'">
              <ul>
                <li v-for="(item, index) in currentResultItem.right_answer" :key="index">
                  <span>{{currentResultItem.right_answer[index].answer_code}}.</span>
                  <el-input class="answer-input" v-model="currentResultItem.right_answer[index].stu_answer" @blur="addResult({type: 13, stu_answer: currentResultItem.right_answer[index].stu_answer, index: index})"/>
                </li>
              </ul>
            </div>
            <!-- 14：翻译题； -->
            <!-- 15：文字排序题； -->
            <!-- 16：连线题； -->
            <!-- 17：写作题； -->
            <!-- 18：口语题 -->
          </div>
          <div class="foot">
            <div class="btn-group-left">
              <el-button type="primary" size="small" :disabled="currentIndex === 0" @click="jumpPage(-1)">上一题</el-button>
              <el-button type="primary" size="small" :disabled="currentIndex === subjectList.length -1" @click="jumpPage(+1)">下一题</el-button>
            </div>
            <div class="btn-group-right">
              <el-button type="primary" size="small" @click="confirm">提交</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { start, submit, updateDuration } from '@/api/student/training/listen'
export default {
  name: 'hearing',
  data () {
    return {
      currentIndex: 0, // 当前题目索引
      timer: null,
      timerDuration: '00:00',
      checkMessage: '', // 任务说明
      hearingData: '', // 听力数据
      subjectList: [], // 题目列表
      resultArr: [], // 完成列表
      lista: []
    }
  },
  async mounted () {
    this.start()
    this.runTimer()
  },
  computed: {
    currentItem () {
      if (this.subjectList) {
        return this.subjectList[this.currentIndex]
      } else {
        return {}
      }
    },
    currentResultItem () {
      return this.resultArr[this.currentIndex]
    }
  },
  methods: {
    openFunc () {
      this.$alert(this.checkMessage, '任务说明',
        { confirmButtonText: '知道了' }
      )
    },
    // 计时
    runTimer () {
      clearInterval(this.timer)
      this.timer = null
      let time = 0
      this.setTime = setInterval(() => {
        time++
        if (time < 60) {
          this.timerDuration = time < 10 ? '00:0' + time : '00:' + time
        } else if (time < 3600) {
          this.timerDuration = Math.floor(time / 60) < 10 ? '0' + Math.floor(time / 60) + ':' + (time % 60 < 10 ? '0' + time % 60 : time % 60) : Math.floor(time / 60) + ':' + (time % 60 < 10 ? '0' + time % 60 : time % 60)
        } else {
          // this.$alert('答题超时，确定后将自动提交', '超时', {
          //   confirmButtonText: '确定'
          // })
          clearInterval(this.setTime)
        }
      }, 1000)
      this.$once('hook:beforeDestroy', () => {
        clearInterval(this.timer)
        this.timer = null
      })
    },
    // 更新作答时长
    async updateDuration () {
      let res = await updateDuration(
        { lessonHearingBatchId: this.hearingData.lessonHearingBatchId }
      )
      if (res.code !== '200') this.$message.error(res.message)
    },
    // 开始训练
    async start () {
      let res = await start(
        {
          lessonHearingCatalogId: this.$route.query.lessonHearingCatalogId,
          resourceHearingId: this.$route.query.resourceHearingId,
          subjectNum: this.$route.query.subjectNum,
          lessonHearingBatchId: this.$route.query.lessonHearingBatchId
        }
      )
      this.hearingData = res.data // 题干
      this.subjectList = res.data.subjectList // 题目
      this.checkMessage = res.data.hearingRemark || '无' // 任务说明
      this.subjectListHandle()
      console.log(res)
    },
    // 数据处理
    subjectListHandle () {
      this.resultArr = this.subjectList.map(item => {
        let resultItem = {
          subject_id: item.subject_id, // 题目id
          subject_type: item.subject_type, // 题目类型
          // stu_answer: '', // 学生作答
          score: 0, // 分数
          right_flag: 0,
          sort_index: item.sort_index // 题目对应的排序号
        }
        // if (Number(item.subject_type) < 17) {
        //   resultItem['right_answer'] = item.right_answer // 正确答案
        //   resultItem['subject_item_id'] = 0 // 正确答案 id
        // }
        if (Number(item.subject_type) === 10 || Number(item.subject_type) === 12) {
          resultItem['stu_answer'] = '' // 学生作答
          resultItem['right_answer'] = item.right_answer // 正确答案
          resultItem['subject_item_id'] = 0 // 正确答案 id
        }
        if (Number(item.subject_type) === 13) {
          let stuAnswerLength = item.right_answer_list.length
          resultItem.right_answer = []
          for (let i = 0; i < stuAnswerLength; i++) {
            resultItem.right_answer.push(
              {
                right_flag: 0,
                stu_answer: '',
                answer_code: item.right_answer_list[i].answer_code,
                right_answer: item.right_answer_list[i].right_answer
              }
            )
          }
        }
        return resultItem
      })
    },
    // 计算得分
    computeScore () {
      let fillArr = this.resultArr[this.currentIndex].right_answer.filter((item) => {
        return item.right_flag === 1
      })
      let score = fillArr.length / this.resultArr[this.currentIndex].right_answer.length * 100
      let rightFlag = fillArr.length === this.resultArr[this.currentIndex].right_answer.length ? 1 : 0
      console.log(fillArr, score, rightFlag)
      return { score: score, rightFlag: rightFlag }
    },
    // 点击选项添加结果
    addResult (resData) {
      console.log(resData)
      if (resData.type === 13) { // 填空题
        if (resData.stu_answer === this.currentResultItem.right_answer[resData.index].right_answer) {
          this.resultArr[this.currentIndex].right_answer[resData.index].right_flag = 1
        }
        this.resultArr[this.currentIndex].score = this.computeScore().score
        this.resultArr[this.currentIndex].right_flag = this.computeScore().rightFlag
      } else if (resData.type === 12) { // 评判题
        this.resultArr[this.currentIndex].stu_answer = resData.subjectItemTent
        this.resultArr[this.currentIndex].subject_item_id = resData.subjectItemId
        if (resData.subjectItemTent === this.currentResultItem.right_answer) {
          this.resultArr[this.currentIndex].score = 100
          this.resultArr[this.currentIndex].right_flag = 1
        }
      } else {
        this.resultArr[this.currentIndex].stu_answer = resData.answerCode
        this.resultArr[this.currentIndex].subject_item_id = resData.subjectItemId
        if (resData.answerCode === this.currentResultItem.right_answer) {
          this.resultArr[this.currentIndex].score = 100
          this.resultArr[this.currentIndex].right_flag = 1
        }
      }
    },
    // 答题卡的active
    cardActive (item, index) {
      let str = this.currentIndex === index ? 'active' : ''
      if (item.subject_type === '13') {
        let alength = item.right_answer.length
        for (let i = 0; i < item.right_answer.length; i++) {
          if (item.right_answer[i].stu_answer) {
            alength--
          }
        }
        return str + (alength === 0 ? 'isAnswer' : '')
      } else {
        return str + (item.stu_answer ? 'isAnswer' : '')
      }
    },
    // 切换题目
    toggleTopic (index) {
      this.currentIndex = parseInt(index)
    },
    // 点击按钮切换题目
    jumpPage (state) {
      this.currentIndex += state
    },
    // 验证未做题目
    checkTopic () {
      let flag = true
      this.resultArr.forEach((item) => {
        if (item.subject_type === '13') {
          let alength = item.right_answer.length
          for (let i = 0; i < item.right_answer.length; i++) {
            if (item.right_answer[i].stu_answer) {
              alength--
            }
          }
          if (alength !== 0) flag = false
        } else {
          if (!item.stu_answer) flag = false
        }
      })
      return flag
    },
    // 提交
    async submit () {
      let score = 0
      this.resultArr.filter(item => {
        score += item.score
      })
      score = Math.round(score / this.resultArr.length)
      console.log(score)
      let params = {
        lessonHearingBatchId: this.hearingData.lessonHearingBatchId,
        resultJson: JSON.stringify(this.resultArr),
        score
      }
      let res = await submit(params)
      console.log(params)
      if (res.code === '200') {
        this.$message({
          type: 'success',
          message: '提交成功'
        })
        setTimeout(() => {
          this.$router.push(
            {
              path: 'hearingreport',
              query: {
                lessonHearingCatalogId: this.$route.query.lessonHearingCatalogId, // 目录id
                resourceHearingId: this.$route.query.resourceHearingId, // 听力题目id
                lessonHearingBatchId: this.hearingData.lessonHearingBatchId // 任务批次id
              }
            }
          )
        }, 200)
      } else {
        this.$message.error(res.message)
      }
    },
    // 确定
    async confirm () {
      console.log(this.checkTopic())
      if (!this.checkTopic()) {
        this.$confirm('确定提交吗?', '当前有题目未完成', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.submit()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        this.submit()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.hearing {
  font-size: 12px;
  height: 100%;
  .container {
    display: flex;
    justify-content: space-between;
    min-height: 100%;
    .box-left {
      width: 630px;
      background: #fff;
      padding: 15px;
      .task-name {
        font-size: 14px;
        margin-bottom: 15px;
        font-weight: bold;
        position: relative;
        i {
          position: absolute;
          right: 20px;
          bottom: -3px;
          font-size: 20px;
          cursor: pointer;
        }
      }
      .media-box {
        background: #f5f5f5;
        border-radius: 10px;
        padding: 15px;
        video {
          width: 570px;
          outline: none;
        }
        audio {
          width: 100%;
        }
      }
    }
    .answer{
      padding: 20px 10px;border-top: solid 1px #eaeaea;margin-top: 20px
    }
    .quesTitle {
      height: 36px;font-size: 16px;font-weight: 500;color: #101d37;padding: 10px;
    }
    .questionBtn {
      display: flex;width: 100%;flex-wrap: wrap;padding: 10px;
      .qBtn {
        color: #91959a;width: calc(15% - 25px);height: 0;text-align: center;margin: 10px;position: relative;padding-bottom: calc(15% - 25px);
        span{
          position: absolute;top: 0;left: 0;width: 100%;height: 100%;border-radius: 3px;display: block;border: 1px solid #91959a;display: flex;align-items: center;justify-content: center;font-size: 18px;
        }
      }
      .qBtn.active span{
        color: #009cf6;border-color: #009cf6;background-color: #fff;border-radius: 3px;
      }
      .qBtn.isAnswer span{
        background-color: #F2F6FC;
      }
      .qBtn:hover span{
        background-color: #EBEEF5;
      }
    }

    .box-right {
      width: 550px;
      text-align: center;
      min-height: 100%;
      background: #fff;
      box-sizing: border-box;
      // .read {
      //   .read-title {
      //     font-size: 18px;
      //     font-weight: bold;
      //   }
      //   .read-desc {
      //     font-size: 14px;
      //     margin: 30px 0;
      //   }
      // }
      // 右侧题目选择
      .question-top {
        text-align: left;
        padding: 0 10px;
        height: 50px;border-bottom: 1px solid #e5e5e5;line-height: 50px;color: #91959a;
        .now-index,.total {
          color: #f86f33;
        }
        .now-index {
          font-size: 26px;
        }
        .total {
          font-size: 16px;
        }
        .time {
          float: right;font-size: 14px;color: #101d37
        }
      }
      .info {
        color: #ff905a;
        width: 430px;
        margin: 0 auto;
        text-align: left;
        border-bottom: 1px solid #efefef;
        padding: 10px 0;
        .step {
          font-size: 20px;
          font-weight: bold;
        }
        .time {
          color: #000;
          margin-left: 40px;
        }
      }
      .sub-panel {
        text-align: left;
        width: 430px;
        margin: 0 auto;
        .stem {
          font-size: 16px;
          margin: 30px 0 20px 0;
        }
        .subject_type_10,.subject_type_12{
          .item {
            font-size: 16px;
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            .chooseBtn {
              color: #91959a;
              width: 35px;
              height: 35px;
              background: #fff;
              border-radius: 50%;
              text-align: center;
              line-height: 35px;
              border: 1px solid #91959a;
              display: block;
            }
            .activeChooseBtn {
              background-color: #009cf6;
              border: 1px solid #009cf6;
              color: #ffffff;
            }
            .question-content {
              margin-left: 10px;
              flex: 1;
              line-height: 1.2;
            }
          }
        }
        .subject_type_12{}
        .subject_type_13{
          li {
            display: flex;
            align-items: center;
            font-size: 18px;
            span {
              margin-right:10px;
            }
          }
          .answer-input {
            margin: 5px 0;
          }
        }
      }
      .foot {
        display: flex;
        justify-content: space-between;
        width: 430px;
        margin: 0 auto;
        margin-top: 30px;
      }
    }
  }
}
</style>
